import 'package:shop/common/AppStorge.dart';
import 'package:shop/common/EventBus.dart';
import 'package:shop/common/UrlConfig.dart';
import 'package:shop/model/memberModel/LoginResponse.dart';
import 'package:shop/model/memberModel/LoginResults.dart';
import 'package:shop/utils/HttpUtils.dart';
import 'package:shop/utils/MyToast.dart';

class MemberService {
  //登录
  Future<bool> login(String userName, String passWord) async {
    LoginResults loginResults = LoginResults()
      ..password = passWord
      ..phone = userName
      ..macNo = "24b5b0e0-ad46-3d30-a7f6-74a1b2191a35"
      ..version = "4.0.0"
      ..platform = "android"
      ..model = "skw-ao"
      ..sysVersion = "10";

    Map map = await MyHttp().post(MyUrl.memberlogin,
        data: loginResults.toJson(), needToken: false, doCatch: false);
    if (map.containsKey("Status") && map["Status"] == 200) {
      LoginResponse loginResponse = LoginResponse.fromJson(map["Data"]);
      //保存token , storeId 到缓存
      MyStorge.token = loginResponse.token;
      MyStorge.storeId = loginResponse.storeId;
      eventBus.fire(UpdataUserEvent());
      return true;
    } else {
      MyToast("${map['Msg']}");
      return false;
    }
  }

  // 发送短信
  Future<bool> sendSms(String phone) async {
    Map results = await MyHttp().post(MyUrl.membersendSms,
        data: {"phone": phone}, needToken: false, doCatch: false);
    if (results.containsKey("Msg")) {
      MyToast("${results['Msg']}");
    }
    return results["Status"] == 200;
  }

  //注册 && 短信登录
  Future<bool> register(String phone, String smscode) async {
    Map results = await MyHttp().post(MyUrl.memberregister,
        data: {
          "phone": phone,
          "sms_code": smscode,
          "gm_code": "1",
          "mac-no": "24b5b0e0-ad46-3d30-a7f6-74a1b2191a35",
          "version": "4.0.0",
          "platform": "android",
          "model": "skw-ao",
          "sys-version": "10"
        },
        doCatch: false,
        needToken: false);

    if (results.containsKey("Status") && results["Status"] == 200) {
      MyStorge.token = results["Data"]["Token"];
      MyStorge.storeId = results["Data"]["StoreId"];
      eventBus.fire(UpdataUserEvent());
      return true;
    } else {
      return false;
    }
  }

  //登出
  Future<bool> loginOut() async {
    Map results = await MyHttp().post(MyUrl.memberloginOut,
        data: {
          "store_id": MyStorge.storeId,
          "mac-no": "24b5b0e0-ad46-3d30-a7f6-74a1b2191a35",
          "version": "4.0.0",
          "platform": "android",
          "model": "skw-ao",
          "sys-version": "10"
        },
        doCatch: false);
    MyStorge.token = "";
    MyStorge.storeId = -1;
    eventBus.fire(UpdataUserEvent());
    return results["Status"] == 200;
  }
}
